package org.osforce.platform.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.osforce.platform.entity.User;
import org.osforce.platform.service.IUserService;
import org.osforce.platform.vo.Page;

import com.opensymphony.xwork2.ModelDriven;

/**
 * 
 * @author gavin
 * 
 */
public class UserAction extends SpringBasedAction implements ModelDriven<User>{

	private static final long serialVersionUID=1950724673940875948L;

	private User user;
	private IUserService userService;
	private Page<User> page;

	public UserAction(){
		this.user=new User();
		this.page=new Page<User>(10);
	}

	public void prepare() throws Exception{
		userService=getBeanByNameAndType("userService",IUserService.class);
	}

	public User getModel(){
		return null;
	}

	@Action(value="/register-user",results={@Result(name=SUCCESS,type="freemarker",location="../../success.ftl")})
	public String registerUser() throws Exception{
		this.userService.registerUser(user);
		return SUCCESS;
	}

	@Action(value="/list-user",results={@Result(name=SUCCESS,type="freemarker",location="../../administractor/user_list.ftl")})
	public String listUser() throws Exception{
		this.page=this.userService.listUserByPage(page);
		return SUCCESS;
	}

	@Action(value="/check-login",results={@Result(name=SUCCESS,type="freemarker",location="success.ftl")})
	public String login() throws Exception{
		User registeredUser=this.userService.loginUser(user);
		if(registeredUser!=null){
			getSession().setAttribute("user",registeredUser);
		}
		return SUCCESS;
	}

	@Action(value="/check-logout",results={@Result(name=SUCCESS,type="freemarker",location="index.ftl")})
	public String logout() throws Exception{
		if(getSession().getAttribute("user")!=null){
			getSession().removeAttribute("user");
		}
		return SUCCESS;
	}

	public User getUser(){
		return user;
	}

	public void setUser(User user){
		this.user=user;
	}

	public Page<User> getPage(){
		return page;
	}

	public void setPage(Page<User> page){
		this.page=page;
	}

}
